﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using System.Web.UI.WebControls;
using ServerApi.Controllers;
using ServerApi.Models;
using TuyennvLibrary.ServerApi.Controllers;
using TuyennvLibrary.ServerApi.Models;
using TuyennvLibrary.Utl;
namespace ServerApi.administrator
{
    public partial class ApplicationManager : System.Web.UI.Page
    {
        ApplicationModel appModel = new ApplicationModel();
        public int stt = 1;
        public string title = "Thêm ứng dụng mới";
        public int item = 2;
        public int count = 0;
        List<FileInfo> filesdll = new List<FileInfo>();
        protected void Page_Load(object sender, EventArgs e)
        {
            AdminController.checkLogin(Session, Request, Response);
            AdminController.checkPermission(Page, this.GetType(), Session, Request, Response);
            if (!IsPostBack)
            {
                loadFileDlls();
                loadClassApi();
                LoadTypeApplication();
                if (!string.IsNullOrEmpty(Request["id"]))
                {
                    string appid = Request["id"];
                    loadinfo(appid);
                    title = "Cập nhật ứng dụng";
                }
                else
                {
                    loadinfo(new Application());
                }
                Search(1);
            }
        }
        private void LoadTypeApplication()
        {
            DataTable dt = new TypeApplicationModel().GetListBy(new string[] { "status" }, new object[] { 1 }, "nameunsign");
            ddlType.DataSource = dt;
            ddlType.DataValueField = "id";
            ddlType.DataTextField = "Name";
            ddlType.DataBind();

            ddlTypeSearch.DataSource = dt;
            ddlTypeSearch.DataValueField = "id";
            ddlTypeSearch.DataTextField = "Name";
            ddlTypeSearch.DataBind();
            ddlTypeSearch.Items.Insert(0, new ListItem { Text = "--Tất cả--", Value = "0" });
        }
        public void loadFileDlls()
        {
            filesdll = TuyennvLibrary.ServerApi.Util.ApiUtilities.getFiles(Server.MapPath(Config.DirFileDLL), new string[] { ".dll" });
            foreach (FileInfo f in filesdll)
            {
                ddlFileDll.Items.Add(new ListItem { Text = f.Name, Value = f.Name });
            }
            ddlFileDll.Items.Insert(0, new ListItem { Text = "TuyennvLibrary.dll", Value = "" });
        }

        public void loadClassApi()
        {
            List<string> list = new List<string>();
            List<string> temp = new List<string>();
            if (ddlFileDll.Text == "")
            {
                temp = TuyennvLibrary.ServerApi.Util.ApiUtilities.GetClasses();
            }
            else
            {
                temp = TuyennvLibrary.ServerApi.Util.ApiUtilities.GetClasses(Assembly.LoadFile(Server.MapPath(Config.DirFileDLL + ddlFileDll.Text)));

            }
            if (temp.Count > 0)
                list.AddRange(temp);
            ddlClassApi.DataSource = list;
            ddlClassApi.DataBind();
        }
        public void Search(int page)
        {
            appModel.page = page;
            appModel.pagesize = 30;
            DataTable dt = appModel.Search(txtIdSearch.Text, txtNameSearch.Text, int.Parse(ddlPlatformSearch.Text), int.Parse(ddlTypeSearch.Text));
            GrvListApp.DataSource = dt;
            GrvListApp.DataBind();
            pager1.PageSize = appModel.pagesize;
            pager1.CurrentIndex = page;
            pager1.ItemCount = appModel.Count;
            count = appModel.Count;


        }

        //private void loadClassApi()
        //{
        //    List<string> listClass = Utilities.GetClasses("ServerApi.Bluesea.ClassApi");
        //    ddlClassApi.DataSource = listClass;
        //    ddlClassApi.DataBind();
        //}
        private void loadinfo(Application app)
        {
            setPannelView(app.platform);
            txtAppid.Text = app.appid;
            txtName.Text = app.name;
            txtapikey.Text = app.api_key;
            ddlType.Text = app.type_app.ToString();
            txtDeveloper.Text = app.developer;
            ddlFileDll.Text = app.file_dll;
            ddlPlatform.Text = app.platform.ToString();
            ddlStatusAdvertise.Text = app.status_advertise.ToString();
            loadClassApi();
            ddlClassApi.Text = app.class_api;
            fmpFileP12.Text = app.filep12;
            txtPassP12.Text = app.passp12;
            txtConfig.Text = app.config;
            txtsenderid.Text = app.sender_id;
        }
        private void loadinfo(string appid)
        {
            Application app = appModel.GetByID(appid);
            loadinfo(app);
        }

        protected void LbtnCancel_Click(object sender, EventArgs e)
        {

        }

        protected void GrvListApp_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton l = (LinkButton)e.Row.FindControl("lbtnDel");
                l.Attributes.Add("onclick", "javascript:return " +
                "confirm('Bạn có muốn xóa ứng dụng này không? " + "')");
            }
        }

        protected void GrvListApp_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string appid = GrvListApp.DataKeys[e.RowIndex].Value.ToString();
            Account acc_current = (Account)Session[AdminController.SESSION_USERCURRENT];
            if (acc_current.Username.ToLower() != "admin")
            {
                Utilities.Alert(Page, this.GetType(), "Bạn không có quyền xóa ứng dụng");
            }
            else
            {
                if (appModel.Delete(appid))
                {
                    Search(1);
                    Utilities.Alert(Page, this.GetType(), "Đã xóa ứng dụng thành công");
                }
            }
        }

        protected void GrvListApp_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GrvListApp.PageIndex = e.NewPageIndex;
            stt = GrvListApp.PageIndex * GrvListApp.PageSize + 1;
            Search(1);
        }

        protected void btnGetLibrary_Click(object sender, EventArgs e)
        {
            try
            {
                string filename = "TuyennvLibrary.dll";
                Response.ContentType = "application/vnd.android.package-archive";
                Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
                filename = Config.DirTempDLL + filename;
                Response.TransmitFile(Server.MapPath(filename));
                Response.End();
            }
            catch (Exception ex)
            {
            }
        }

        protected void ddlFileDll_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadClassApi();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Search(1);
        }

        protected void btnAddTypeApp_Click(object sender, EventArgs e)
        {
            Response.Redirect("TypeApplicationManager.aspx");
        }

        protected void btnViewDescriptionClass_Click(object sender, EventArgs e)
        {
            Response.Redirect("DescriptionClassManager.aspx");
        }

        protected void ddlPlatform_SelectedIndexChanged(object sender, EventArgs e)
        {
            setPannelView(int.Parse(ddlPlatform.Text));
        }
        private void setPannelView(int platform)
        {
            if (platform == 1)
            {
                pnAndroid.Visible = true;
                pnIOS.Visible = false;
            }
            else if (platform == 2)
            {
                pnIOS.Visible = true;
                pnAndroid.Visible = false;
            }
            else
            {
                pnIOS.Visible = false;
                pnAndroid.Visible = false;
            }
        }
        protected void pager1_Command(object sender, CommandEventArgs e)
        {
            int currnetPageIndx = Convert.ToInt32(e.CommandArgument);
            Search(currnetPageIndx);
        }

        protected void btnAccept_Click(object sender, EventArgs e)
        {
            Application app = new Application();
            app.appid = txtAppid.Text;
            app.name = txtName.Text;
            app.api_key = txtapikey.Text;
            app.status = 1;
            app.private_key = Utilities.md5(app.appid);
            app.platform = int.Parse(ddlPlatform.Text);
            app.status_advertise = int.Parse(ddlStatusAdvertise.Text);
            if (!string.IsNullOrEmpty(txtConfig.Text))
            {
                app.config = txtConfig.Text;
            }

            app.developer = txtDeveloper.Text;

            app.filep12 = fmpFileP12.Text;

            app.passp12 = txtPassP12.Text;
            app.file_dll = ddlFileDll.Text;

            if (string.IsNullOrEmpty(ddlClassApi.Text))
            {
                app.class_api = Config.PACKAGE_CLASS_API + ".GeneralApi";
            }
            else
            {
                //app.class_api = Config.PACKAGE_CLASS_API + "." + ddlClassApi.Text;
                app.class_api = ddlClassApi.Text;
            }
            app.sender_id = txtsenderid.Text;
            app.type_app = int.Parse(ddlType.Text);
            if (!string.IsNullOrEmpty(Request["id"]))
            {
                if (appModel.Update(app))
                {
                    Utilities.Alert(Page, this.GetType(), "Đã cập nhật ứng dụng thành công");
                    Response.Redirect("ApplicationManager.aspx");
                }
            }
            else
            {
                appModel.Insert(app);
                Utilities.Alert(Page, this.GetType(), "Đã thêm mới ứng dụng thành công");
            }
            Search(1);
        }
    }
}